import os
import pathlib
import base64
import wave
import struct
import pytest
from intelli_port.commons.config import load_settings
from tests.utils.db_setup import setup_all

def _ensure_dirs():
    pathlib.Path("tests/fixtures").mkdir(parents=True, exist_ok=True)
    pathlib.Path("artifacts").mkdir(parents=True, exist_ok=True)

def _touch(path: str):
    p = pathlib.Path(path)
    if not p.exists():
        p.write_bytes(b"")

def _write_sample_wav(path: str):
    try:
        framerate = 16000
        duration = 0.2
        amp = 16000
        freq = 440.0
        with wave.open(path, 'wb') as w:
            w.setnchannels(1)
            w.setsampwidth(2)
            w.setframerate(framerate)
            for i in range(int(framerate * duration)):
                val = int(amp * 0.5 * (i % (framerate // int(freq)) < (framerate // int(freq)) // 2))
                w.writeframes(struct.pack('<h', val))
    except Exception:
        _touch(path)

def _write_sample_png(path: str):
    try:
        png_b64 = (
            "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAHElEQVQoU2NkYGD4z0AEYBxVQ"
            "wMDAwMDAgAEADjgBCtIhOe4AAAAASUVORK5CYII="
        )
        data = base64.b64decode(png_b64)
        pathlib.Path(path).write_bytes(data)
    except Exception:
        _touch(path)

@pytest.fixture(scope="session", autouse=True)
def bootstrap_test_data():
    _ensure_dirs()
    _write_sample_wav("tests/fixtures/sample.wav")
    _write_sample_png("tests/fixtures/sample.png")
    if not os.getenv("MYSQL_URI"):
        os.environ["MYSQL_URI"] = "mysql://root:root@localhost:3306/airport_test"
    load_settings()
    setup_all()
    yield